// @charset "utf-8";

define(function(require, exports, module) {
	var publicMethod = require('../../public/public'),
		clientApi = require('../../public/clientapi');

	// var ClientQuote = require('../../public/clientquote');
	var IndexBase = require('../allindex/indexbase');

	function MarketModule() {
		this.domId = 'market';
		this.MODULENAME = '上证指数';
		this.EXPLAINTEXT = '';

		this.type = 'min';

		this.code = '1A0001';
		this.indexCode = '1A0001';
		this.hcType = '';

		this.latestVal1 = '--';
		this.latestVal2 = '--';

		this.tradeDay = '';
		this.zdfObj = {};
		this.volObj = {};
		this.zdfArr = [];
		this.preData = 1;
		this.HighchartsObj = null;
		this.thsQuote = external.createObject('Quote');
		this.renderDom();
	}

	publicMethod.extendClass(MarketModule, IndexBase);

	MarketModule.prototype.renderDom = function () {
		var self = this;
		var htmlDom = '<li data-mname="'+ self.domId +'">' +
					'<div class="module-item">' +
						'<div class="module-header">' +
							'<a href="###" class="icon module-close-btn"></a>' +
							// '<div class="date-wrap">' +
							// 	'<p class="date-wrap-single">' +
							// 		'<input type="text" class="icon date-picker" value="2017-02-16" id="'+ self.domId + 'DatePicker" />' +
							// 		'<a href="###" class="icon interval-btn" title="切换区间" id="'+ self.domId + 'IntervalBtn"></a>' +
							// 	'</p>' +
							// 	'<p class="date-wrap-interval hide">' +
							// 		'<input type="text" class="icon date-picker" value="2017-02-16" id="'+ self.domId + 'SDatePicker" />' +
							// 		'<i class="separator">-</i>' +
							// 		'<input type="text" class="icon date-picker" value="2017-02-16" id="'+ self.domId + 'EDatePicker"  />' +
							// 		'<a href="###" class="icon single-btn" title="切换区间" id="'+ self.domId + 'SingleBtn"></a>' +
							// 	'</p>' +
							// '</div>' +
							'<p class="module-name">'+ self.MODULENAME +'</p>' +
						'</div>' +
						'<div class="module-main">' +
							'<div class="chart-box" id="'+ self.domId +'ChartBox">' +
							'</div>' +
							// '<div class="explain-box hide" id="'+ self.domId +'ExplainBox">' +
							// 	'<p class="explain-text">'+ self.EXPLAINTEXT +'</p>' +
							// 	'<div class="clearfix">' +
							// 	'<div class="explain-left '+ self.domId +'-explain-pic">' +
							// 	'</div>' +
							// 	'<div class="explain-right">' +
							// 		'<p>今日解读：<span id="'+ self.domId +'ExplainData">放量净流入12亿</span></p>' +
							// 		'<br/>' +
							// 		'<p>上涨概率回测</p>' +
							// 		'<p id="'+ self.hcType +'HcData"><a href="###" class="hc-link"><span>实时提示两市个股涨跌停的数量。涨跌停数量反应了短期市场的强弱，涨停个股越多，市场越强；反之需警惕市场走弱。</span><i class="details">查看详情&gt;</i></a></p>' +
							// 	'</div>' +
							// 	'</div>' +
							// '</div>' +
							// '<p class="non-trade-tip" id="'+ self.domId +'NonTradeTip">非交易日，请重新选择</p>' +
						'</div>' +
					'</div>' +
				'</li>';
				$('#modules-list-ul').append(htmlDom);
				self.requestData();

	}
	MarketModule.prototype.requestData = function() {
		var self = this;
		var tradeDay = clientApi.getTradingDay();
		self.tradeDay = tradeDay;
		var quoteType = 'ZQMC,10,2525646,VOL,SETTLE,6';
		var getType = '10,2525646,VOL,QHZD';

		var getData = function(param) {
			var rst = self.thsQuote.getData2({
				type: quoteType,
				code: '1A0001',
				period: 'min',
				time: {
					begin: tradeDay,
					end: tradeDay,
					timeFmt: 1
				},
				updateMode: 1,
				timeStamp: 1
			});

			var zs = self.thsQuote.getData2({
				type: '6',
				code: '1A0001',
				period: 'now'
			});

			rstData = eval('(' + rst + ')');
			zsData = eval('(' + zs + ')');
			self.preData = zsData['1A0001']['6'];
			self.analyticalData(rstData, tradeDay);
		};
		self.thsQuote.request({
			type: quoteType,
			code: '1A0001',
			period: 'min',
			begin: tradeDay,
			end: tradeDay,
			timeFmt: 1,
			onready: getData
		});

		self.thsQuote.registerPush({
			code: '1A0001',
			// onready: function(p) {
			// 	self.getQuoteData(stocks, quote);
			// }
			onready: publicMethod.throttle(getData, 10000, self)
		});
	}

	MarketModule.prototype.cancelPush = function() {
		this.thsQuote.unregisterPush();
	}

	MarketModule.prototype.analyticalData = function(data, tradeDay) {
		var self = this;
		var xjArr = [],
			zdfArr = [],
			zdfObj = {},
			volObj = {};
		var j = 0;
		$.each(data['1A0001'], function(i, val) {
			xjArr.push(parseFloat(val['10']));

			zdfObj[publicMethod.xAxisData[j]] = parseFloat(val['2525646']).toFixed(2);
			volObj[publicMethod.xAxisData[j]] = parseFloat(val['VOL']).toFixed(2);
			zdfArr.push(val['2525646']);
			// volObj.push(parseFloat(val['VOL']));
			j++;
		});

		self.zdfObj = zdfObj;
		self.volObj = volObj;
		self.zdfArr = zdfArr;
		// self.drawChart(xjArr, zdfObj, volObj, tradeDay, zdfArr);

		var priceCur = xjArr[xjArr.length - 1];
		var zdCur = parseFloat(priceCur - self.preData).toFixed(2);
		var zdfCur = parseFloat(self.zdfArr[self.zdfArr.length - 1]).toFixed(2);
		var _color = '#fff',
			_lift = '';
		if (zdfCur > 0) {
			_color = 'red';
			_lift = '↑';
		} else if (zdfCur < 0) {
			_color = 'green';
			_lift = '↓';
		}
		var dynamic = '';
		if (!isNaN(priceCur) && !isNaN(zdfCur)) {
			dynamic = '<p class="market-legend ' + _color + '">' + priceCur + ' ' + _lift + ' ' + zdCur + ' (' + zdfCur + '%)</p>'
		}

		if (self.HighchartsObj) {
			self.HighchartsObj.series[0].update({
				data: xjArr
			});
			$('.market-legend').removeClass('red green').addClass(_color).text(priceCur + ' ' + _lift + ' ' + zdCur + ' (' + zdfCur + '%)');
		} else {
			self.drawChart(xjArr, dynamic);
		}
	}

	MarketModule.prototype.drawChart = function(xjArr, dynamic) {
		var self = this;

		var _tickPositions = [0, 120, 241],
			_tickInterval = '120',
			_xAxisMin = '0',
			_xAxisMax = '241',
			_xAxisData = publicMethod.xAxisData;
		var chartOptions = {
			credits: {
				enabled: false
			},
			title: {
				text: dynamic,
				useHTML: true,
				style: {
					fontSize: '12px',
					fontFamily: 'Microsoft yahei',
					fontWeight: 'bold'
				},
				x: -120
			},
			chart: {
				backgroundColor: null,
				style: {
					"fontFamily": "Arial, \"Microsoft yahei\", Verdana, Helvetica, sans-serif",
					"fontSize": "12px"
				},
				marginTop: 40,
				marginLeft: 40,
				marginBottom: 30
			},
			series: [{
				name: '上证指数',
				type: 'area',
				// color: '#0186e4',
				// lineWidth: 1,
				// marker: {
				// 	enabled: false,
				// states: {
				// 	hover: {
				// 		fillColor: '#0186e4',
				// 		radius: 2,
				// 		lineColor: 'rgba(4, 103, 174, 1)',
				// 		lineWidthPlus: 1
				// 	}
				// }
				// },
				data: xjArr
			}],
			plotOptions: {
				series: {
					stickyTracking: false
				},
				area: {
					fillColor: {
						linearGradient: {
							x1: 0,
							y1: 0,
							x2: 0,
							y2: 1
						},
						stops: [
							[0, '#083a5f'],
							[1, Highcharts.Color('#0b1016').setOpacity(0).get('rgba')]
						]
					},
					marker: {
						radius: 2,
						states: {
							hover: {
								fillColor: '#0186e4',
								radius: 2,
								lineColor: '#fff',
								lineWidthPlus: 1
							}
						}
					},
					lineWidth: 1,
					lineColor: '#0186e4',
					states: {
						hover: {
							lineWidth: 1
						}
					},
					threshold: null
				}
			},
			xAxis: {
				lineWidth: 1,
				tickLength: 4,
				lineColor: '#808080',
				tickColor: '#808080',
				tickInterval: _tickInterval,
				tickPositions: _tickPositions,
				title: {
					text: ''
				},
				categories: _xAxisData,
				gridLineWidth: 0,
				labels: {
					align: 'center',
					rotation: 0,
					style: {
						color: '#afafaf'
					}
				},
				min: _xAxisMin,
				max: _xAxisMax
			},
			yAxis: {
				allowDecimals: false,
				lineWidth: 1,
				tickColor: '#808080',
				tickPosition: 'outside',
				gridLineWidth: 0,
				tickLength: 4,
				tickWidth: 1,
				title: {
					text: ''
				},
				lineColor: '#808080',
				labels: {
					style: {
						color: '#afafaf'
					},
					x: -7
				}
			},
			legend: {
				enabled: false,
				align: 'right',
				verticalAlign: 'top',
				floating: false,
				symbolHeight: 10,
				symbolWidth: 14,
				itemStyle: {
					color: '#dedede',
					fontFamily: 'Microsoft yahei',
					fontWeight: 'normal'
				},
				itemHiddenStyle: {},
				itemHoverStyle: {
					color: '#bbb'
				},
				useHTML: true
			},
			tooltip: {
				shared: true,
				backgroundColor: '#2e3339',
				borderColor: '#505458',
				shape: '',
				crosshairs: [{
					width: 1,
					color: '#afafaf'
				}],
				valueDecimals: 2,
				style: {
					fontFamily: 'Microsoft yahei',
					color: '#fff'
				},
				useHTML: true,
				formatter: function() {
					var color = '#fff';
					var zdfCur = self.zdfObj[this.x];
					if (zdfCur > 0) {
						color = 'red';
					} else if (zdfCur < 0) {
						color = 'green';
					}
					var head = self.tradeDay + ' ' + this.x + ' ' + '(北京时间)';
					var dqj = '当前价：&nbsp; ' + (this.y).toFixed(2);
					var zdf = '涨跌幅：&nbsp; <i class="' + color + '">' + self.zdfObj[this.x] + '%</i>';
					var vol = '成交量：&nbsp; ' + (self.volObj[this.x] / 1000000).toFixed(2) + '万手';
					return head + '<br/>' + dqj + '<br/>' + zdf + '<br/>' + vol;
				}
			}
		};

		$('#' + self.domId + 'ChartBox').highcharts(chartOptions);
		self.HighchartsObj = $('#' + self.domId + 'ChartBox').highcharts();
	}

	MarketModule.prototype.updateSeries = function (isHasOverall, date) {
		var self = this;
		if (date != self.tradeDay) {
			self.requestData();
		}
	}

	module.exports = MarketModule;
});